import { useLocalStorageStore } from '@/stores/localStore'
import { useAsyncAxios } from '@/utils/asyncFuncStore'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useModalStore } from '@/stores/modalStore'
import { useCurrActStroe } from '@/stores/currActStore'
import type { Act, ErrorData, FormSuccessData } from '@/types/loginType'
export default function () {
  const { changeData } = useModalStore()
  //   账号列表
  const { accounts } = storeToRefs(useLocalStorageStore())
  //   存储
  const { setLocal, removeLocal, removeToken, setToken } = useLocalStorageStore()
  // 异步请求
  const { loginJWT } = useAsyncAxios()
  //   路由跳转
  const router = useRouter()

  //   列表提交数据
  async function submitData(item: Act) {
    // 设置对话人的token
    // 重置当前token
    setToken(item.token)
    const { status, data } = await loginJWT()
    if (status === 200) {
      const { token, id, user, img, ...returnData } = data as FormSuccessData
      // 更新值
      const { assignCurrUser } = useCurrActStroe()
      assignCurrUser({ id, name: user, img, ...returnData })
      changeData({ status: status, data: { msg: '登录成功' } })
      removeLocal(id)
      setLocal({ id, user, img, token })
      setTimeout(() => {
        router.push('/index')
      }, 800)
    } else {
      // 错误弹窗
      const { msg } = data as ErrorData
      if (status === 401) {
        // 身份过期，移除 token 和账号记录
        setTimeout(() => {
          removeToken()
          removeLocal(item.id)
        }, 800)
      }
      changeData({ status: status, data: { msg: msg } })
    }
  }
  // 删除登录信息
  const deleteAccount = (key: string) => {
    // [{id, user, img, token}, {}]
    try {
      accounts.value.forEach((e) => {
        if (e.id === key) {
          removeLocal(key)
          return true
        }
      })
    } catch (error) {
      return false
    }
  }

  const localValue = localStorage.getItem('aLis')
  accounts.value = JSON.parse(localValue !== null ? localValue : '[]')

  return {
    accounts,
    submitData,
    deleteAccount
  }
}
